package com.hksj.cbm.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hksj.cbm.dto.DeviceDTO;
import com.hksj.cbm.entity.DeviceInstance;
import com.hksj.cbm.entity.SpaceModel;
import com.hksj.cbm.mapper.DeviceInstanceMapper;
import com.hksj.cbm.query.DeviceInstanceQuery;
import com.hksj.cbm.vo.DeriveMetadataVO;
import com.hksj.cbm.vo.SpaceModelVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author fjt
 * @data 2024/7/10 15:18
 * @describe 设备信息
 */
@Slf4j
@Service
public class DeviceInstanceService extends ServiceImpl<DeviceInstanceMapper, DeviceInstance> {


    @Autowired
    private SpaceModelService spaceModelService;



    /**
     * 查询指定空间位置下指定专业的全部设备
     * @param dto
     * @return
     */
    public List<DeviceInstance> deviceList(DeviceDTO dto){
        return baseMapper.deviceList(dto);
    }


    /**
     * 批量设备位置路径转中文
     * @param pathList 数据库中保存的设备路径，如：10,11,12,13,14
     * @return 形如：10,11,12,13,14 : List<SpaceModelVO>
     */
    public Map<String, List<SpaceModelVO>> devicePathConvertToUTF8(List<String> pathList){
        Assert.notEmpty(pathList, "设备路径集合不能为空");
        pathList = pathList.stream().filter(item -> StringUtils.isNotBlank(item)).collect(Collectors.toList());
        List<Long> pathIdList = new ArrayList<>();
        pathList.forEach(path -> {
            List<Long> listId = Arrays.stream(path.split(",")).map(id -> Long.parseLong(id)).collect(Collectors.toList());
            pathIdList.addAll(listId);
        });
        if (CollUtil.isEmpty(pathIdList)){
            return null;
        }

        List<SpaceModel> spaceList = spaceModelService.listByIds(pathIdList);
        Map<String, SpaceModel> spaceModelMap = spaceList.stream().collect(Collectors.toMap(p -> p.getId().toString(), p -> p));
        if (CollUtil.isEmpty(spaceModelMap)){
            return null;
        }

        Map<String, List<SpaceModelVO>> pathNameMap = new HashMap<>(pathList.size());
        for (String path : pathList){
            List<SpaceModelVO> spaceModelVOList = new ArrayList<>();
            for(String str : path.split(",")){
                if (ObjectUtil.isNotEmpty(spaceModelMap.get(str))) {
                    SpaceModelVO modelVO = new SpaceModelVO();
                    BeanUtils.copyProperties(spaceModelMap.get(str), modelVO);
                    spaceModelVOList.add(modelVO);
                }
            }
            pathNameMap.put(path, spaceModelVOList);
        }
        return pathNameMap;
    }


    /**
     * 获取指定设备的检测指标
     * @param deviceId
     * @return 设备监测指标key : 指标相关信息
     */
    public Map<String, DeriveMetadataVO> getDeviceAttribute(String deviceId){
        DeviceInstance deviceInstance = baseMapper.selectDeviceInstanceById(deviceId);
        if (ObjectUtil.isNull(deviceInstance)){
            throw new RuntimeException("数据异常！id为：" + deviceId + "的设备不存在");
        }
        // 设备监测指标key : 指标相关信息
        Map<String, DeriveMetadataVO> attributeMap = new HashMap<>();

        // 1.解析设备所属产品的物模型
        String productMetadata = deviceInstance.getProductMetadata();
        if (ObjectUtil.isNotEmpty(productMetadata)){
            Map<String, DeriveMetadataVO> productAttributeMap = analysisProductAttribute(productMetadata);
            if (CollUtil.isNotEmpty(productAttributeMap)){
                attributeMap.putAll(productAttributeMap);
            }
        }

        // 2.解析设备自身的物模型
        String deriveMetadata = deviceInstance.getDeriveMetadata();
        if (ObjectUtil.isNotEmpty(deriveMetadata)){
            Map<String, DeriveMetadataVO> deviceAttributeMap = analysisProductAttribute(deriveMetadata);
            if (CollUtil.isNotEmpty(deviceAttributeMap)){
                attributeMap.putAll(deviceAttributeMap);
            }
        }
        return attributeMap;
    }


    /**
     * 解析设物模型
     * @param productMetadata
     * @return
     */
    /** 设备所属的产品的物模型
     * {"properties":[
     * {"id":"Adwzt","name":"日间手术室","expands":{"source":"device","type":["read","write","report"]},"valueType":{"type":"int"}},
     * {"id":"Bdwzt","name":"手术室01","expands":{"source":"device","type":["read","write","report"]},"valueType":{"type":"int"}},
     * {"id":"Cdwzt","name":"急诊手术室","expands":{"source":"device","type":["read","write","report"]},"valueType":{"type":"int"}},
     * {"id":"Ddwzt","name":"手术室02","expands":{"source":"device","type":["read","write","report"]},"valueType":{"type":"int"}}]}
     */
    /** 设备自身的物模型
     *{"properties":[{"id":"temperature","name":"温度","expands":{"source":"device","type":["read","write","report"]},
     * "valueType":{"unit":"celsiusDegrees","scale":2,"type":"float"}}]}
     */
    private Map<String, DeriveMetadataVO> analysisProductAttribute(String productMetadata){
        String properties = JSONObject.parseObject(productMetadata).getString("properties");
        if (StringUtils.isBlank(properties)){
            return null;
        }
        Map<String, DeriveMetadataVO> attributeMap = new HashMap<>();
        JSONArray array = JSONArray.parseArray(properties);
        for (int i = 0; i < array.size(); i++) {
            // 属性key和名称
            JSONObject jsonObject = array.getJSONObject(i);
            String key = jsonObject.getString("id");
            if (StringUtils.isBlank(key)){
                continue;
            }
            DeriveMetadataVO metadataVO = DeriveMetadataVO.builder().key(key).keyName(jsonObject.getString("name")).build();

            // 读写状态
            String readWriteStatus = JSONObject.parseObject(jsonObject.getString("expands")).getString("type");
            List<String> readWriteStatusList = JSONArray.parseArray(readWriteStatus, String.class);
            metadataVO.setReadWriteStatus(readWriteStatusList);

            // 属性值的数据类型
            String dataType = JSONObject.parseObject(jsonObject.getString("valueType")).getString("type");
            metadataVO.setDataType(dataType);

            //属性值的单位
            String unit = String.valueOf(JSONObject.parseObject(jsonObject.getString("valueType")).getOrDefault("unit", ""));
            metadataVO.setUnit(unit);
            attributeMap.put(key, metadataVO);
        }
        return attributeMap;
    }


    /**
     * 批量获取指定设备的检测指标
     * @param deviceIdList
     * @return 设备id : <设备监测指标key : 指标相关信息>
     */
    public Map<String, Map<String, DeriveMetadataVO>> batchQueryDeviceAttribute(List<String> deviceIdList){
        Map<String, Map<String, DeriveMetadataVO>> map = new HashMap<>();
        List<DeviceInstance> deviceInstanceList = baseMapper.selectDeviceInstanceBatchIds(deviceIdList);
        if (CollUtil.isEmpty(deviceInstanceList)){
            return map;
        }

        for(DeviceInstance instance : deviceInstanceList){
            // 设备监测指标key : 指标相关信息
            Map<String, DeriveMetadataVO> attributeMap = new HashMap<>();
            // 1.解析所属产品的物模型
            String productMetadata = instance.getProductMetadata();
            if (ObjectUtil.isNotEmpty(productMetadata)){
                Map<String, DeriveMetadataVO> productAttributeMap = analysisProductAttribute(productMetadata);
                if (CollUtil.isNotEmpty(productAttributeMap)){
                    attributeMap.putAll(productAttributeMap);
                }
            }

            // 2.解析设备自身的物模型
            String deriveMetadata = instance.getDeriveMetadata();
            if (ObjectUtil.isNotEmpty(deriveMetadata)){
                Map<String, DeriveMetadataVO> deviceAttributeMap = analysisProductAttribute(deriveMetadata);
                if (CollUtil.isNotEmpty(deviceAttributeMap)){
                    attributeMap.putAll(deviceAttributeMap);
                }
            }
            if (CollUtil.isNotEmpty(attributeMap)){
                map.put(instance.getId(), attributeMap);
            }
        }
        return map;
    }

    /**
     * 分页查询设备列表
     */
    public Page<DeviceInstance> queryDeviceInstanceListByPaging(DeviceInstanceQuery deviceInstanceQuery){

        //创建分页实例
        Page<DeviceInstance> page = new Page<>(deviceInstanceQuery.getPageNum(),deviceInstanceQuery.getPageSize());

        //查询未绑定的实体设备
        deviceInstanceQuery.setBindDeviceModelStatus(0);

        //分页查询
        List<DeviceInstance> deviceInstanceList = baseMapper.queryDeviceInstanceListByPaging(page, deviceInstanceQuery);

        //将查询结果设置到分页
        page.setRecords(deviceInstanceList);

        return page;
    }


}






